

class ProjectController extends BaseController{
    def beforeInterceptor = [action:this.auth]
    
    def index = { redirect(action:list,params:params) }

    // the delete, save and update actions only accept POST requests
    static allowedMethods = [delete:'POST', save:'POST', update:'POST']

    def list = {
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
        if(session.access.equals("admin")){
            if(DBConnection.isConnectionStarted()){
                [ projectInstanceList: DBConnection.getProjectList(), projectInstanceTotal: DBConnection.getProjectCount() ]
            }
            else{
                [ projectInstanceList: Project.list( params ), projectInstanceTotal: Project.count() ]
            }
        }
        else{
            def access = session.access
            access.refresh()
            def list = access.getList("project")
            //println("hmmm: " + list)

            [ projectInstanceList: list, projectInstanceTotal: list.count() ]
            
        }
    }

    def show = {
        def projectInstance

        // test if transaction started
        if(DBConnection.isConnectionStarted()){
            projectInstance = DBConnection.getProject(params.id)
        }
        else{
            projectInstance = Project.get( params.id )
        }

        if(!projectInstance) {
            flash.message = "Project not found with id ${params.id}"
            redirect(action:list)
        }
        else {
            
            // test if the project is available in current mode
            if(ModeAccess.isAvailableInCurrentMode(session.mode,projectInstance.mode)){
                // If the project mode corresponds to the current mode
                if(session.access.equals("admin")){
                    return [
                        projectInstance : projectInstance,
                        numberOfEmployees: projectInstance.getListOfEmployees().size()
                    ]
                }
                def access = session.access
                access.refresh()
                println("Area ID: " + projectInstance.area.id)
                if(access.checkAccess("project", "show", projectInstance.area.id)){
                    return [
                        projectInstance : projectInstance,
                        numberOfEmployees: projectInstance.getListOfEmployees().size()
                    ]
                }
                else{
                    flash.message = "Missing Authorization!"
                    redirect(action:list)
                }
            }
            else{
                flash.message = "Project not accessible in current mode"
                redirect(action:list)
            }

        }
    }

    def delete = {
            //System.out.println(params.id)
            // test if transaction started
            def projectInstance
            if(DBConnection.isConnectionStarted()){
                projectInstance = DBConnection.getProject(params.id)
            }
            else{
                projectInstance = Project.get( params.id )
            }

            if(projectInstance) {
                try {
                    projectInstance.delAllEmployees()
                    if(DBConnection.isConnectionStarted()){
                        DBConnection.deleteProject(projectInstance.id)
                    }
                    else{
                        projectInstance.delete(flush:true)
                    }
                    flash.message = "Project ${params.id} deleted"
                    redirect(action:list)
                }
                catch(org.springframework.dao.DataIntegrityViolationException e) {
                    flash.message = "Project ${params.id} could not be deleted"
                    redirect(action:show,id:params.id)
                }
            }
            else {
                flash.message = "Project not found with id ${params.id}"
                redirect(action:list)
            }
        
    }

    def edit = {
        //test if transaction started
        def projectInstance
        if(DBConnection.isConnectionStarted()){
            projectInstance = DBConnection.getProject(params.id)
        }
        else{
            projectInstance = Project.get( params.id )
        }

        if(!projectInstance) {
            flash.message = "Project not found with id ${params.id}"
            redirect(action:list)
        }
        else {
            // test if the project can be edited in current mode
            if(ModeAccess.isAvailableInCurrentMode(session.mode,projectInstance.mode)){
                return [ projectInstance : projectInstance ]
            }
            else{
                flash.message = "Project not accessible in current mode"
                redirect(action:list)
            }
        }
    }

    def update = {
        def projectInstance
        if(DBConnection.isConnectionStarted()){

            projectInstance = DBConnection.getProject( params.id )
            if(projectInstance) {
                projectInstance.properties = params
                if(!projectInstance.hasErrors()) {
                    DBConnection.updateProject(projectInstance)
                    flash.message = "Project ${projectInstance} updated in sandbox"
                    redirect(action:show,id:projectInstance.id)
                }
                else {
                    render(view:'edit',model:[projectInstance:projectInstance])
                }
            }
            else {
                flash.message = "Project not found with id ${params.id}"
                redirect(action:list)
            }
        }
        else{
            projectInstance = Project.get( params.id )
            if(projectInstance) {
                if(params.version) {
                    def version = params.version.toLong()
                    if(projectInstance.version > version) {

                        projectInstance.errors.rejectValue("version", "project.optimistic.locking.failure", "Another user has updated this Project while you were editing.")
                        render(view:'edit',model:[projectInstance:projectInstance])
                        return
                    }
                }
                projectInstance.properties = params
                if(!projectInstance.hasErrors() && projectInstance.save()) {
                    flash.message = "Project ${projectInstance} updated"
                    redirect(action:show,id:projectInstance.id)
                }
                else {
                    render(view:'edit',model:[projectInstance:projectInstance])
                }
            }
            else {
                flash.message = "Project not found with id ${params.id}"
                redirect(action:list)
            }
        }
    }

    def create = {
        def projectInstance = new Project()

        projectInstance.properties = params        
        return ['projectInstance':projectInstance]
    }

    def save = {
        if(params.mode.equalsIgnoreCase("budget")){
            params.mode=0
        }
        else{
            params.mode=1
        }
        def projectInstance = new Project(params)        
        
        if(projectInstance.currentBudget().variableCosts == null || projectInstance.currentBudget().variableCosts.isEmpty())
        {
            for(CostCategory costCategory : CostCategory.list())
            {
                projectInstance.currentBudget().addToVariableCosts(amount:(Float)0, category:costCategory )
            }
        }

        if(!projectInstance.hasErrors()) {
                if(DBConnection.isConnectionStarted()){
                    Integer idP
                    if((idP=DBConnection.saveProject(projectInstance))>0){
                        flash.message = "Project ${idP} created"
                        redirect(action:show,id:idP)
                    }
                    else{
                        render(view:'create',model:[projectInstance:projectInstance])
                    }
                }
                else{
                    if(projectInstance.save()){
                        flash.message = "Project ${projectInstance} created"
                        redirect(action:show,id:projectInstance.id)
                    }
                    else{
                        render(view:'create',model:[projectInstance:projectInstance])
                    }
                }

        }
        else {
            render(view:'create',model:[projectInstance:projectInstance])
        }
    }

    def add_employee = {
        def p
        if(DBConnection.isConnectionStarted()){
            p = DBConnection.getProject(params.id)
        }
        else{
            p = Project.get(params.id);
        }
        println("project:"+p)
        ArrayList<Employee> l = new ArrayList<Employee>();
            // test if the project is available in current mode
            if(ModeAccess.isAvailableInCurrentMode(session.mode,p.mode)){
                // If the project mode corresponds to the current mode
                def employeeList
                if(DBConnection.isConnectionStarted()){
                    employeeList = DBConnection.getEmployeeList()
                }
                else{
                    employeeList = Employee.list()
                }

            println("employeeList:"+employeeList)
                for(Employee e : employeeList){
                    int wantedMode
                    if(session.mode == null || session.mode.equalsIgnoreCase("sandbox")){ // if current mode = sandbox
                       wantedMode=1  
                    }
                    else{   // if current mode = budget
                        wantedMode=0
                    }
                    //TODO Modification in order to avoid employee from other container to show up there
                    def pList = p.getListOfEmployees()
                    println("plist:"+pList)
                    boolean trouve=false
                    for(Employee emp:pList){
                        if(emp.equals(e)){
                            trouve=true
                            break
                        }
                    }
                    if(!trouve && e.mode==wantedMode){
                        println("emode:"+e.mode)
                        l.add(e);
                    }
                }
                render(view:'add_employee',model:[ employeeList: l, projectid: params.id ])
            }
            else{
                flash.message = "Project not accessible in current mode"
                redirect(action:list)
            }
    }

    def save_added_employee = {
        String[] vals = request.getParameterValues("employeeid")
        println("vals:"+vals)
        def projectInstance
        if(DBConnection.isConnectionStarted()){
            projectInstance = DBConnection.getProject(params.projectid)
        }
        else{
            projectInstance = Project.get( params.projectid )
        }

        if (projectInstance) {
            for(String v : vals){
                println("val"+v)
                def employee
                if(DBConnection.isConnectionStarted()){
                    employee = DBConnection.getEmployee(v)
                }
                else{
                    employee = Employee.get( v )
                }
                println("employeePC:"+employee)
                println("projectPC:"+projectInstance)
                if(employee == null) {
                    System.out.println(v + " fel!");
                }
                else{
                    projectInstance.addEmployee(employee);
                }
            }

            println("projectPC2:"+projectInstance)
            println("project ici:"+projectInstance.amountOfHour)
           
            if(!DBConnection.isConnectionStarted()){
                if(projectInstance.save(flush:true,validate:false)) {
                    if(vals!=null && vals.length>=1){
                        flash.message = "New employee(s) added"
                    }
                    else{
                        flash.message = "No employee added"
                    }
                }
                else{
                    flash.message = "Cannot add new employee"

                    projectInstance.errors.each {
                        println (it);
                    }
                }
            }
            redirect(action:show, id : params.projectid)
        }
        else{
            flash.message = "Project \"${projectInstance.name}\" not found with id ${params.projectid}"
            redirect(action:list)
        }

    }
    def delete_employee = {
        int wantedMode
        if(session.mode == null || session.mode.equalsIgnoreCase("sandbox")){ // if current mode = sandbox
           wantedMode=1
        }
        else{   // if current mode = budget
            wantedMode=0
        }
        def projectInstance
        if(DBConnection.isConnectionStarted()){
            projectInstance = DBConnection.getProject(params.id)
        }
        else{
            projectInstance = Project.get( params.id )
        }

        List<Employee> l = projectInstance.getListOfEmployeesByMode(wantedMode)
        
        [ employeeList: l, id: params.id ]
    }

    def save_deleted_employee = {
        String[] del = request.getParameterValues("employeeid")
        def projectInstance
        if(DBConnection.isConnectionStarted()){
            projectInstance = DBConnection.getProject(params.id)
        }
        else{
            projectInstance = Project.get( params.id )
        }
        println("delete from project:"+projectInstance)
        println("to del:"+del)
        for(String x : del){
             // add information about the mode
            def empl
            if(DBConnection.isConnectionStarted()){
                empl = DBConnection.getEmployee(x)
            }
            else{
                empl = Employee.get( x )
            }
            println("got employee:"+empl)
            projectInstance.delEmployee(empl)


        }
        if(del!=null && del.length>=1){
            flash.message = "Employee(s) deleted from the project"
        }
        else{
            flash.message = "No employee deleted"
        }
        redirect(action:show, id : params.id)
    }

    def updateIncome = {
        Float newIncome = Float.parseFloat(params.figure);

        def projectInstance = Project.get(params.id);

        Budget b = projectInstance?.currentBudget();

        if(params.typeOfIncome == "expectedIncome"){
            b.expectedTotalIncome = newIncome;
        }
        else{
             b.knownTotalIncome = newIncome;
        }
        if(projectInstance.save(flush:true)){
                
        }
        else{
             projectInstance.errors.each {
                  println(it);
                }
                b.errors.each {
                 println(it);
                }
        }

        redirect(action:blank);
        
    }

    def updateVariableCost =
    {
        Float newCost = Float.parseFloat(params.figure);
        def projectInstance = Project.get(params.id);
        Budget b = projectInstance?.currentBudget();

        if(!params.idVariableCost.startsWith("variableCost_"))
        {
            flash.message = "Incorrect variable_cost_id"
            redirect(action:blank);
        }
       

        int vId= (int)Integer.parseInt(params.idVariableCost.replace("variableCost_",""))
        VariableCost cost = null
        for(VariableCost vCost: b.variableCosts)
        {
            if(vCost.id == vId)
            {
                cost=vCost
                break
            }
        }

        if(cost == null)
        {
            flash.message = "Tried to edit a nonexistant cost"
            redirect(action:blank);
        }

        cost.amount = newCost

        if(projectInstance.save(flush:true)){

        }
        else{
             projectInstance.errors.each {
                  println(it);
                }
                b.errors.each {
                 println(it);
                }
        }
        redirect(action:blank);
    }

    def changeMode = {
        //System.out.println("-"+session.mode+"-")
        if((session.mode==null)||(!session.mode.equalsIgnoreCase("budget"))){
              session.mode="budget"
              DBConnection.rollbackTransaction()
        }
        else{
            session.mode="sandbox"
            DBConnection.connect()
            DBConnection.startTransaction()

        }
        //System.out.println("-"+session.mode+"-")

        flash.message = "Mode changed"
        if(params.idProject.equals("null")){
            redirect(controller:params.currentController,action:params.currentView)
        }
        else{
            redirect(controller:params.currentController,action:params.currentView, id:params.idProject)
        }
    }

    def blank = {}
    
}
